// 项目库-项目列表

import React from 'react';
import { observer, useLocalStore } from 'mobx-react-lite';
import { Link } from 'react-router-dom';
import { Form, DatePicker, Button, Input, Card, Row, Col, Pagination, message, Modal } from 'antd';
import {
  SearchOutlined, PlusSquareOutlined,
} from '@ant-design/icons';
import * as listApi from '~/apis/project/listApi';
import AjaxSelect from '~/components/AjaxSelect';
import { config } from '~/config/config';
import { getColumns } from './pageConfig';
import '~/styles/project.local.sass';

// 声明顶部SearchForm组件
const { RangePicker } = DatePicker;

const FormItem = Form.Item;

const showTotal = (total: number) => `Total: ${total}`;

const cardConfig = {
  size: 'small' as const,
  bordered: false,
};

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};


const ProjectMy = observer(() => {
  const state = useLocalStore(() => ({
    loading: false,
    tableList: {
      data: [],
      pageNo: 1,
      pageSize: 8,
      totalCount: 0,
      totalPage: 0,
    },
    getData: {} as any,
  }));

  const [form] = Form.useForm();

  const doQuery = (curPage: number = 1) => {
    state.tableList.pageNo = curPage;

    const { pageNo, pageSize } = state.tableList;

    // 时间戳处理
    const { time } = state.getData;
    let startTime = null;
    let endTime = null;
    if (time && time.length > 0) {
      startTime = new Date(time[0]).getTime();
      endTime = new Date(time[1]).getTime();
    }

    const params = {
      pageNum: pageNo,
      pageSize,
      startTime,
      endTime,
      ...state.getData,
    };

    delete params.time;

    state.loading = true;

    listApi.getMyProjectList(params).then((res) => {
      state.tableList = {
        ...state.tableList,
        data: res.data,
        totalCount: res.pageInfo ? res.pageInfo.total : 0,
        totalPage: res.pageInfo ? res.pageInfo.totalPages : 0,
      };
    }).finally(() => {
      state.loading = false;
    });
  };

  const onSearch = (values: any) => {
    state.getData = values;

    doQuery(1);
  };

  const onReset = () => {
    form.resetFields();
  };

  const columns = getColumns(ProjectMy);

  // 项目上下架
  const handleShelve = (id: string, status: number) => {
    const _status: number = status ? 0 : 1;
    listApi.handleShelve({ id, status: _status }).then(() => {
      message.success('success!');
      doQuery();
    });
  };

  const { confirm } = Modal;
  // 删除项目
  const handleProjectDelete = (id: string) => {
    confirm({
      title: 'Do you Want to delete this project?',
      onOk() {
        listApi.handleProjectDelete(id).then(() => {
          message.success('delete success!');
          doQuery();
        });
      },
    });
  };

  const { loading,
    tableList: {
      pageNo, totalCount, pageSize, data,
    } } = state;

  const tableOption: any = {
    loading,
    columns,
    pagination: {
      current: pageNo,
      total: totalCount,
      pageSize,
      size: 'small',
      showQuickJumper: true,
      showTotal,
      onChange: (curPage: number) => {
        doQuery(curPage);
      },
    },
    dataSource: data || [],
    rowKey: 'id',
    size: 'small',
    // bordered: true,
  };

  React.useEffect(() => {
    doQuery(1);
  }, []);


  const timestampToTime = (timestamp: any) => {
    const date = new Date(timestamp);// 时间戳为10位需*1000，时间戳为13位的话不需乘1000
    const Y = `${date.getFullYear()}/`;
    const M = `${date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1}/`;
    const D = `${date.getDate()} `;
    return Y + M + D;
  };


  // 项目列表渲染
  const myProjectList = tableOption.dataSource;
  // const checkStatus = ['New', 'Viewed', 'Rectified'];
  const myProjectListItems: any = [];
  const imgUrl = config.ossUrl;
  myProjectList.forEach((item: any) => {
    myProjectListItems.push(
      <li key={item.id}>
        <Link to={`/project/details?id=${item.id as string}`} >
          <div className="list-container">
            <span className="avatar">
              {
                (() => {
                  if (item.thumbnail) {
                    return (<img src={`${imgUrl}${item.thumbnail as string}`} alt='' className="avatar-img"/>);
                  }
                  return <></>;
                })()
              }
            </span>
            <div className="project-content">
              <div className="project-title">
                <span></span>
                <b>{item.projectTitle}</b>
              </div>
              <div className="project-detail">
                <p>Country/Region:  <em>{item.countryName}</em></p>
                <p>Investment:  <em>{item.totalAmount}</em></p>
                <p>Project stage:  <em>{item.stageName}</em></p>
                <p>Publish time:  <em>{timestampToTime(item.startingTime)}</em></p>
              </div>
            </div>

          </div>
        </Link>
        <div className="bottom-tag">
          <button><Link to={`/project/edit?id=${item.id as string}`} >Edit</Link></button>
          <button onClick={() => handleShelve(item.id, item.status)}>{ item.status === 1 ? 'Suspend' : 'Publish'}</button>
          <button onClick={() => handleProjectDelete(item.id)}>Delete</button>
        </div>
        <div className="top-tag">
          <p className={ item.status === 0 ? 'Pending' : ''}>{item.status === 0 ? 'Pending' : ''}</p>
          {/* <p className={checkStatus[item.auditStatus]}>{checkStatus[item.auditStatus]}</p> */}
        </div>
      </li>,
    );
  });

  return (
    <div>
      {/* 顶部搜索栏 */}
      <div className="project-search">
        <Card {...cardConfig} className="search-card">
          <Form form={form} onFinish={onSearch}>
            <Row>
              <Col span={4}>
                <Form.Item name="time" {...formItemLayout}>
                  <RangePicker
                    format="YYYY-MM-DD"
                    placeholder={['Start Time', 'End Time']}
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </Col>
              <Col span={4}>
                <Form.Item name="countryId" shouldUpdate={true} {...formItemLayout}
                >
                  <AjaxSelect
                    placeholder="Country/Region"
                    type="countryList"
                  />
                </Form.Item>
              </Col>
              <Col span={4}>
                <FormItem name="industryId" {...formItemLayout}
                >
                  <AjaxSelect
                    placeholder="Industry"
                    type="industryList"
                  />
                </FormItem>
              </Col>

              <Col span={4}>
                <Form.Item name="stageCode" {...formItemLayout} >
                  <AjaxSelect
                    placeholder="Project stage"
                    type="projectStage"
                  />
                </Form.Item>
              </Col>
              <Col span={4}>
                <FormItem name="projectName" {...formItemLayout} >
                  <Input
                    allowClear={true}
                    onPressEnter={onSearch}
                    prefix={
                      <SearchOutlined style={{ color: '#A9B8CF' }}/>
                    }
                  />
                </FormItem>
              </Col>
              <Col span={2}>
                <FormItem {...formItemLayout}>
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="mr-2"
                    block
                  >
                    Search
                  </Button>
                </FormItem>
              </Col>
              <Col span={2}>
                <FormItem {...formItemLayout}>
                  <Button className="mr-2" onClick={onReset} block>
                    Reset
                  </Button>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Card>
      </div>


      <div className="project-list">
        <ul >
          <li className="new-project">
            <Link to={'/project/new'}>
              <div>
                <PlusSquareOutlined style={{ fontSize: '32px', color: '#9DAFCC', marginTop: '2px' }} />
              </div>
            </Link>
            <p>New project</p>
          </li>
          {myProjectListItems}
        </ul>
      </div>

      <div>
        <Pagination
          showQuickJumper
          defaultCurrent={1}
          total={tableOption.pagination.total}
          showTotal={(total) => `Total ${total}`}
          pageSize={7}
          onChange={tableOption.pagination.onChange} />
      </div>


    </div>
  );
});


export default ProjectMy;
